package com.lin.fengxiu.repository;

import com.lin.fengxiu.model.UserCoupon;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import javax.swing.text.html.Option;
import java.util.Optional;

/**
 * @ClassName UserCouponRepository
 * @Description TODO 用户与优惠券关系
 * @Author wushaopei
 * @Date 2021/3/28 22:16
 * @Version 1.0
 */
@Repository
public interface UserCouponRepository  extends JpaRepository<UserCoupon,Long> {

    /**
     * @Description TODO 根据 uid 和 couponId 、status 查询的UserCoupon
     * @param uid
     * @param couponId
     * @param status
     * @return
     */
    Optional<UserCoupon> findFirstByUserIdAndCouponIdAndStatus(Long uid, Long couponId, int status);

    /**
     * @Description TODO 查询用户是否已经领取过优惠券
     * @param uid
     * @param couponId
     * @return
     */
    Optional<UserCoupon> findFirstByUserIdAndCouponId(@Param("uid") Long uid, @Param("couponId") Long couponId);

    /**
     * @Description TODO 优惠券核销
     * @param couponId
     * @param oid
     * @param uid
     * @return
     */
    @Modifying
    @Query("update UserCoupon uc\n" + "set uc.status = 2, uc.orderId = :oid\n" + "where uc.userId = :uid\n" + "and uc.couponId = :couponId\n" + "and uc.status = 1 \n" + "and uc.orderId is null")
    int writeOff(@Param("couponId") Long couponId, @Param("oid") Long oid, @Param("uid") Long uid);


    /**
     * @Description TODO 优惠券归还
     * @param couponId
     * @param uid
     * @return
     */
    @Modifying
    @Query("update UserCoupon c\n" + "set c.status=1, c.orderId = null \n" + "where c.couponId=:couponId\n" + "and c.userId = :uid\n" + "and c.orderId is not null\n" + "and c.status = 2")
    int returnBack(Long couponId, Long uid);
}
